package com.openapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.common.utils.SnowFlakeIDGenerator;
import com.openapi.business.MediaControlEntry;
import com.openapi.business.RealtimeMediaUploadCmd;
import com.openapi.business.RealtimeMediaUploadReq;
import com.openapi.common.entity.ServerHeart;
import com.openapi.common.utils.R;
import com.openapi.config.KafkaProducerConfig;
import com.openapi.config.RedisConfig;
import com.openapi.config.VedioAdressMapConfig;
import com.openapi.protocol.ServerHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@Api(description = "视频中间服务处理API")
public class VideoController {
    private static final Logger log = LoggerFactory.getLogger(ServerHandler.class);
    public static final String TOPIC_DISTRIBUTE_DATA = "distributeData";
    public static final String DISTRIBUTE_MSG_TOPIC = "RealtimeMediaUploadReq_Send";
    public static final String DISTRIBUTE_CMD_TOPIC = "RealtimeMediaUploadCmd_Send";
    @Autowired
    RedisConfig redisConfig;
    @Autowired
    KafkaProducerConfig kafkaProducerConfig;

    public VideoController() {
    }

    @ApiOperation("流媒体控制")
    @CrossOrigin
    @ApiImplicitParams({@ApiImplicitParam(
            name = "controllerPath",
            paramType = "path",
            allowableValues = "video45controller",
            required = true
    ), @ApiImplicitParam(
            name = "msgoperation",
            value = "流媒体控制0：下发通知并上线 1：关闭视频",
            dataType = "int",
            paramType = "query"
    ), @ApiImplicitParam(
            name = "devid",
            value = "终端设备id",
            dataType = "string",
            paramType = "query",
            required = true
    ), @ApiImplicitParam(
            name = "channel",
            value = "通道号",
            dataType = "int",
            paramType = "query",
            required = true
    ), @ApiImplicitParam(
            name = "streamtype",
            value = "流媒体类型 0音视频 1视频 2音频",
            dataType = "int",
            paramType = "query",
            required = true
    )})
    @PostMapping({"/{controllerPath}/streamingMediaControl"})
    @ResponseBody
    public R getElectricFence(HttpServletRequest request) throws Exception {
        R r = new R();
        MediaControlEntry mediaControlEntry = new MediaControlEntry();
        mediaControlEntry.devid = request.getParameter("devid");
        mediaControlEntry.channel = Integer.parseInt(request.getParameter("channel"));
        mediaControlEntry.action = 4;
        mediaControlEntry.streamtype = Integer.parseInt(request.getParameter("streamtype"));
        mediaControlEntry.url = "";
        mediaControlEntry.vh = 0;
        mediaControlEntry.vw = 0;
        mediaControlEntry.vfps = 0;
        JSONObject object = new JSONObject();
        object.put("msgtype", 3);
        object.put("body", mediaControlEntry.toJSONString());
        int msgoperation = Integer.parseInt(request.getParameter("msgoperation"));
        if (0 == msgoperation) {
            HashOperations<String, String, ServerHeart> hashOperations = this.redisConfig.redisTemplate().opsForHash();
            List<ServerHeart> hearts = hashOperations.values("HeartBeatInfo1077");
            if (hearts.size() == 0) {
                log.info(" c++视频服务不在线");
                r.put("code", "300");
                r.put("msg", "c++视频服务不在线");
                return r;
            }

            hearts = hearts.stream().sorted(Comparator.comparing(ServerHeart::getConnected)).collect(Collectors.toList());
            String serverName = (hearts.get(0)).getServername();

            log.info(serverName);
            ServerHandler.sendMsg(serverName, object.toString());
            ServerHeart curheart = hearts.get(0);
            int servernameIndex = VedioAdressMapConfig.getServerNameBean().indexOf(curheart.servername);
            String serviceIp = VedioAdressMapConfig.getMapServerAddressBean().get(servernameIndex);
            int portindex = VedioAdressMapConfig.getInnerPortBean().indexOf(curheart.serverport);
            int port = Integer.parseInt(VedioAdressMapConfig.getOutsidePortBean().get(portindex));


            RealtimeMediaUploadReq realtimeMediaUploadReq = new RealtimeMediaUploadReq();
            realtimeMediaUploadReq.ip = serviceIp;
            realtimeMediaUploadReq.tcpPort = port;
            realtimeMediaUploadReq.udpPort = 0;
            realtimeMediaUploadReq.chanelId = mediaControlEntry.channel;
            realtimeMediaUploadReq.mediaType = mediaControlEntry.streamtype;
            realtimeMediaUploadReq.codeType = 1;
            realtimeMediaUploadReq.devNo = mediaControlEntry.devid;
            realtimeMediaUploadReq.distributeMsgTopic = DISTRIBUTE_MSG_TOPIC;;
            realtimeMediaUploadReq.msgId = (int)Long.parseLong("9101", 16);
            long id = SnowFlakeIDGenerator.getInstance().nextId();
            realtimeMediaUploadReq.requestId = id + "";
            realtimeMediaUploadReq.userId = "123456";
            realtimeMediaUploadReq.userName = "wupeng";
            realtimeMediaUploadReq.distributeTime = new Date();
            realtimeMediaUploadReq.serialNo = 123456;
            log.info(" realtimeMediaUploadReq 下发通知并上线" + realtimeMediaUploadReq.toJSONString().toString());
            this.kafkaProducerConfig.kafkaTemplate().send(TOPIC_DISTRIBUTE_DATA, realtimeMediaUploadReq.toJSONString().toString());
        } else if (1 == msgoperation) {
            RealtimeMediaUploadCmd realtimeMediaUploadCmd = new RealtimeMediaUploadCmd();
            realtimeMediaUploadCmd.chanelId = mediaControlEntry.channel;
            realtimeMediaUploadCmd.CmdType = 0;
            realtimeMediaUploadCmd.CloseMediaType = 0;
            realtimeMediaUploadCmd.devNo = mediaControlEntry.devid;
            realtimeMediaUploadCmd.distributeMsgTopic =DISTRIBUTE_CMD_TOPIC;
            realtimeMediaUploadCmd.msgId = (int)Long.parseLong("9102", 16);
            long id = SnowFlakeIDGenerator.getInstance().nextId();
            realtimeMediaUploadCmd.requestId = id + "";
            realtimeMediaUploadCmd.userId = "123456";
            realtimeMediaUploadCmd.userName = "wupeng";
            realtimeMediaUploadCmd.distributeTime = new Date();
            realtimeMediaUploadCmd.serialNo = 123456;
            log.info(" realtimeMediaUploadCmd 视频下线" + realtimeMediaUploadCmd.toJSONString().toString());
            this.kafkaProducerConfig.kafkaTemplate().send(TOPIC_DISTRIBUTE_DATA, realtimeMediaUploadCmd.toJSONString().toString());
        } else {
            log.info(" 参数错误");
        }

        try {
            r.put("code", "0");
            r.put("msg", "success");
            return r;
        } catch (Exception var19) {
            r.put("code", "1");
            r.put("msg", var19.getMessage());
            return r;
        } finally {
            ;
        }
    }
}




